<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';

import type { FormDefinitionForm } from '#/api/workflow/formDefinition/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { Col, Form, FormItem, Input, Row } from 'ant-design-vue';
import { pick } from 'lodash-es';

import {
  formDefinitionAdd,
  formDefinitionInfo,
  formDefinitionUpdate,
} from '#/api/workflow/formDefinition';
import { useBeforeCloseDiff } from '#/utils/popup';
import FormDesigner from '#/views/workflow/components/form-designer.vue';

import { emitter } from './mitt';

const emit = defineEmits<{ reload: [] }>();
const formDesigner = ref<FormDesigner>(null);
const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<FormDefinitionForm> = {
  formId: null,
  formName: null,
  formContent: null,
  formDescription: null,
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<FormDefinitionForm>>({
  formName: [{ required: true, message: '表单名称不能为空' }],
  formPublishStatus: [{ required: true, message: '发布状态不能为空' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreen: true,
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleSubmit,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await formDefinitionInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
      // 编辑回填 构造动态表单 formSchema
      emitter.emit('formSchema', JSON.parse(formData.value.formContent));
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleSubmit() {
  if (formDesigner.value) {
    formDesigner.value.saveSchema();
  }
}

async function handleConfirm(data) {
  console.log('回传设计器数据=>', data);
  formData.value.formContent = JSON.stringify(data);
  try {
    modalApi.lock(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value
      ? formDefinitionUpdate(data)
      : formDefinitionAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  formData.value = defaultValues;
  resetFields();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 5 }">
      <Row class="z-10 w-[100%]">
        <Col :span="9">
          <FormItem
            label="表单名称"
            v-bind="validateInfos.formName"
            class="mb-0 leading-[3]"
          >
            <Input
              v-model:value="formData.formName"
              :placeholder="$t('ui.formRules.required')"
            />
          </FormItem>
        </Col>
        <Col :span="14">
          <FormItem
            label="描述说明"
            v-bind="validateInfos.formDescription"
            class="mb-0 leading-[3]"
          >
            <Input
              v-model:value="formData.formDescription"
              :placeholder="$t('ui.formRules.required')"
            />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="24">
          <FormDesigner ref="formDesigner" @save-schema="handleConfirm" />
        </Col>
      </Row>
    </Form>
  </BasicModal>
</template>
